package com.rwind.druid.config.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

public abstract class AbstractDataSourceConfig {

  public abstract DataSource dataSource();

  public abstract String getMapperLocation();

  public abstract String getMybatisConfigLocation() ;
  
  public DataSourceTransactionManager transactionManager(DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);
    // 加载全局的配置文件
    sqlSessionFactoryBean
        .setConfigLocation(new DefaultResourceLoader().getResource(getMybatisConfigLocation()));
    sqlSessionFactoryBean.setPlugins(new Interceptor[] {});

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    sqlSessionFactoryBean.setMapperLocations(resolver.getResources(getMapperLocation()));

    return sqlSessionFactoryBean.getObject();
  }



}